<?php

ini_set("display_errors", "On");
error_reporting(E_ALL);

// 引入数据库连接文件
require_once '../../../sql/connection.php';

$courseID = $_POST['addID'];
$classID = $_POST['addClassID'];

// 查询语句
$querySql = "select id, create_time, update_time, course_ID, class_ID from `course-class` where class_ID ='$classID' and course_ID = '$courseID' and is_delete = 0";
// 连接数据库，并查询
$result = mysqli_query($GLOBALS['conn'], $querySql);
// 查询语句
$querySql2 = "select id, create_time, update_time, course_ID, class_ID from `course-class` where class_ID ='$classID' and course_ID = '$courseID' and is_delete = 1";
// 连接数据库，并查询
$result2 = mysqli_query($GLOBALS['conn'], $querySql2);

//echo $result_config;
if (mysqli_num_rows($result) > 0) {
	echo "
<script>
    alert('该课程已关联，请重新关联！');
    history.go(-1);
</script>";
}

else if (mysqli_num_rows($result2) > 0)
{
	$now = date('Y-m-d H:i:s', time());
	$addSql = "UPDATE `course-class` set update_time = '$now',is_delete = 0 where class_ID ='$classID' and course_ID = '$courseID';";
	if (mysqli_query($GLOBALS['conn'], $addSql)) {
		echo "
            <script>
                alert('关联成功！');
                window.location.href=document.referrer;
            </script>
        ";
	} else {
		echo "
            <script>
                alert('关联失败！');
                history.back();
            </script>
        ";
	}
}
else{
	$now = date('Y-m-d H:i:s', time());
	$addSql = "INSERT INTO `course-class`(create_time, update_time, class_ID , course_ID ,is_delete)VALUES ('$now','$now','$classID','$courseID', 0)";
	if (mysqli_query($GLOBALS['conn'], $addSql)) {
		echo "
            <script>
                alert('关联成功！');
                window.location.href=document.referrer;
            </script>
        ";
	} else {
		echo "
            <script>
                alert('关联失败！');
                history.back();
            </script>
        ";
	}
	
}

